//
//  UserViewController.m
//  iengage
//
//  Created by Luis Ziliani on 2/13/09.
//  Copyright 2009 Manas. All rights reserved.
//

#import "UserViewController.h"
#import "Util.h"
#import "iengageAppDelegate.h"

@implementation UserViewController

@synthesize user, webView, navigationController;

- (NSString *) getHTMLForUser {
	NSMutableString *html = [[[NSMutableString alloc] initWithString:@"<html><head></head><body>"] autorelease];
	[html appendString:@"<img src='data:image/jpg;base64, "];
	[html appendString:[user imageData]];
	[html appendString:@"' alt='' /><br><br>"];
	[html appendString:@"<b>Said:</b><br>"];
	[html appendString: [[user lastMessage] toHTML]];
	[html appendString:@"<br>"];
	[html appendString:[user lastMessageDateDifferenceFromNow]];
	[html appendString:@"<img src='http://maps.google.com/staticmap?center="];
	NSString * locationString = [NSString stringWithFormat:@"%.12f,%.12f", [user latitude], [user longitude]];
	[html appendString:locationString];
	[html appendString:@"&amp;zoom=14&amp;size=256x256&amp;maptype=mobile&amp;markers="];
	[html appendString:locationString];
	[html appendString:@",blue"];
	[html appendString:[[[user displayName] substringToIndex:1] lowercaseString]];
	[html appendString:@"&amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSsTL4WIgxhMZ0ZK_kHjwHeQuOD4xQJpBVbSrqNn69S6DOTv203MQ5ufA' alt='User location' />"];
	[html appendString:@"</body></html>"];
	return html;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil user:(User*)userToShow {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		[self setUser: userToShow];
		self.title = [user displayName];
	}
	return self;
}

- (void) saveState {
	IEngageAppDelegate * app = [[UIApplication sharedApplication] delegate];
	[[app appState] setLastUserViewed: [user login]];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[webView loadHTMLString:[self getHTMLForUser] baseURL:nil];
	
	[self saveState];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (IBAction)gotoMap: (id)sender {
	@try {
		NSString *urltxt = [NSString stringWithFormat:@"http://maps.google.com/?q=%@ says %@@%f,%f&z=15", [user displayName], [user lastMessage], [user latitude], [user longitude]];
		NSString *fixedURL = [urltxt stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		NSString *bla = [fixedURL stringByReplacingOccurrencesOfString:@"%20" withString:@"%A0"];
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:bla]];
	}
	@catch (NSException * e) {
		
	}
}


- (void)dealloc {
	[user release];
	[webView release];
    [super dealloc];
}


@end
